<template>
  <div class="api-templates-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>接口开发模板</h1>
          <p>优质API开发框架模板，助力后端服务快速开发</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ templates.length }}</span>
            <span class="stat-label">模板数量</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ totalDownloads }}</span>
            <span class="stat-label">总下载数</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filters-section">
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索框架名称、技术栈..."
          prefix-icon="Search"
          size="large"
          clearable
        />
      </div>
      <div class="filter-tabs">
        <el-radio-group v-model="activeLanguage" size="large">
          <el-radio-button label="all">
            全部
          </el-radio-button>
          <el-radio-button label="java">
            Java
          </el-radio-button>
          <el-radio-button label="nodejs">
            Node.js
          </el-radio-button>
          <el-radio-button label="python">
            Python
          </el-radio-button>
          <el-radio-button label="golang">
            Go
          </el-radio-button>
          <el-radio-button label="csharp">
            C#
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 模板卡片网格 -->
    <div class="templates-grid">
      <div
        v-for="template in filteredTemplates"
        :key="template.id"
        class="template-card"
        @click="viewTemplate(template)"
      >
        <!-- 模板封面 -->
        <div class="template-cover">
          <div class="framework-logo">
            <img :src="template.logo" :alt="template.name">
          </div>
          <div class="cover-overlay">
            <div class="overlay-actions">
              <el-button type="primary" size="large" @click.stop="downloadTemplate(template)">
                <el-icon><Download /></el-icon>
                立即下载
              </el-button>
              <el-button size="large" @click.stop="viewDocumentation(template)">
                <el-icon><Document /></el-icon>
                查看文档
              </el-button>
            </div>
          </div>

          <!-- 语言标签 -->
          <div class="language-tag">
            <el-tag :type="getLanguageTagType(template.language)" size="large">
              {{ template.language }}
            </el-tag>
          </div>

          <!-- 难度等级 -->
          <div class="difficulty-badge">
            <el-rate
              v-model="template.difficulty"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </div>
        </div>

        <!-- 模板信息 -->
        <div class="template-info">
          <h3 class="template-title">
            {{ template.name }}
          </h3>
          <p class="template-description">
            {{ template.description }}
          </p>

          <div class="template-meta">
            <div class="meta-left">
              <span class="author">
                <el-icon><User /></el-icon>
                {{ template.author }}
              </span>
              <span class="version">
                <el-icon><PriceTag /></el-icon>
                v{{ template.version }}
              </span>
            </div>
            <div class="meta-right">
              <span class="downloads">
                <el-icon><Download /></el-icon>
                {{ formatNumber(template.downloads) }}
              </span>
              <span class="stars">
                <el-icon><Star /></el-icon>
                {{ template.stars }}
              </span>
            </div>
          </div>

          <div class="template-features">
            <el-tag
              v-for="feature in template.features.slice(0, 3)"
              :key="feature"
              size="small"
              effect="plain"
            >
              {{ feature }}
            </el-tag>
            <span v-if="template.features.length > 3" class="more-features">
              +{{ template.features.length - 3 }}
            </span>
          </div>

          <!-- 技术栈图标 -->
          <div class="tech-icons">
            <el-tooltip
              v-for="tech in template.techStack.slice(0, 5)"
              :key="tech"
              :content="tech"
              placement="top"
            >
              <div class="tech-icon">
                <img :src="getTechIcon(tech)" :alt="tech">
              </div>
            </el-tooltip>
            <div v-if="template.techStack.length > 5" class="more-tech">
              +{{ template.techStack.length - 5 }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button size="large" @click="loadMore" :loading="loading">
        加载更多模板
      </el-button>
    </div>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedTemplate?.name"
      width="950px"
      class="template-detail-dialog"
    >
      <div v-if="selectedTemplate" class="template-detail">
        <div class="detail-header">
          <div class="detail-logo">
            <img :src="selectedTemplate.logo" :alt="selectedTemplate.name">
          </div>
          <div class="detail-info">
            <h2>{{ selectedTemplate.name }}</h2>
            <p class="detail-description">
              {{ selectedTemplate.fullDescription }}
            </p>

            <div class="detail-meta">
              <div class="meta-item">
                <span class="label">开发语言：</span>
                <el-tag :type="getLanguageTagType(selectedTemplate.language)">
                  {{ selectedTemplate.language }}
                </el-tag>
              </div>
              <div class="meta-item">
                <span class="label">难度等级：</span>
                <el-rate
                  v-model="selectedTemplate.difficulty"
                  disabled
                  size="small"
                />
              </div>
              <div class="meta-item">
                <span class="label">作者：</span>
                <span class="value">{{ selectedTemplate.author }}</span>
              </div>
              <div class="meta-item">
                <span class="label">版本：</span>
                <span class="value">v{{ selectedTemplate.version }}</span>
              </div>
              <div class="meta-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ selectedTemplate.updateTime }}</span>
              </div>
              <div class="meta-item">
                <span class="label">下载次数：</span>
                <span class="value">{{ formatNumber(selectedTemplate.downloads) }}</span>
              </div>
            </div>

            <div class="detail-actions">
              <el-button type="primary" size="large" @click="downloadTemplate(selectedTemplate)">
                <el-icon><Download /></el-icon>
                下载模板
              </el-button>
              <el-button size="large" @click="viewDocumentation(selectedTemplate)">
                <el-icon><Document /></el-icon>
                查看文档
              </el-button>
              <el-button size="large" @click="openGiteeRepo(selectedTemplate)">
                <el-icon><Link /></el-icon>
                Gitee仓库
              </el-button>
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="content-section">
            <h3>技术栈</h3>
            <div class="tech-stack-detail">
              <div
                v-for="tech in selectedTemplate.techStack"
                :key="tech"
                class="tech-item"
              >
                <img :src="getTechIcon(tech)" :alt="tech">
                <span>{{ tech }}</span>
              </div>
            </div>
          </div>

          <div class="content-section">
            <h3>功能特性</h3>
            <ul class="features-list">
              <li v-for="feature in selectedTemplate.features" :key="feature">
                <el-icon><Check /></el-icon>
                {{ feature }}
              </li>
            </ul>
          </div>

          <div class="content-section">
            <h3>API示例</h3>
            <div class="api-examples">
              <div
                v-for="(example, index) in selectedTemplate.apiExamples"
                :key="index"
                class="api-example"
              >
                <h4>{{ example.title }}</h4>
                <pre><code>{{ example.code }}</code></pre>
              </div>
            </div>
          </div>

          <div class="content-section">
            <h3>项目结构</h3>
            <div class="project-structure">
              <pre>{{ selectedTemplate.projectStructure }}</pre>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Check, Document, Download, Link, PriceTag, Star, User } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, onMounted, ref } from "vue"

interface ApiExample {
  title: string
  code: string
}

interface ApiTemplate {
  id: string
  name: string
  description: string
  fullDescription: string
  logo: string
  author: string
  version: string
  updateTime: string
  downloads: number
  stars: number
  language: string
  difficulty: number
  techStack: string[]
  features: string[]
  apiExamples: ApiExample[]
  projectStructure: string
  giteeUrl: string
  documentationUrl: string
}

// 响应式数据
const searchText = ref("")
const activeLanguage = ref("all")
const loading = ref(false)
const hasMore = ref(true)
const detailDialogVisible = ref(false)
const selectedTemplate = ref<ApiTemplate | null>(null)

// 模板数据
const templates = ref<ApiTemplate[]>([
  {
    id: "knife4j-spring-boot",
    name: "Knife4j Spring Boot Template",
    description: "基于Knife4j的Spring Boot API开发模板",
    fullDescription: "基于Spring Boot + Knife4j的企业级API开发模板。集成了Spring Security、MyBatis Plus、Redis、Knife4j等常用技术栈，提供完整的权限管理、用户认证、API文档等功能。Knife4j提供了比Swagger更优雅的API文档界面。",
    logo: "https://knife4j.xiaominfo.com/assets/logo-bf7a25a9.png",
    author: "cheng-long-x",
    version: "3.0.3",
    updateTime: "2025-03-18",
    downloads: 28900,
    stars: 856,
    language: "Java",
    difficulty: 3,
    techStack: ["Spring Boot", "Knife4j", "MyBatis Plus", "Redis", "MySQL", "Spring Security"],
    features: ["Knife4j文档", "JWT认证", "权限管理", "缓存支持", "统一异常处理", "日志管理", "数据校验", "接口测试"],
    apiExamples: [
      {
        title: "用户登录接口",
        code: `@Api(tags = "用户认证")
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = authService.login(loginDTO);
        return Result.success(new LoginVO(token));
    }
}`
      },
      {
        title: "Knife4j配置",
        code: `@Configuration
@EnableKnife4j
public class Knife4jConfig {
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}`
      }
    ],
    projectStructure: `src/
├── main/
│   ├── java/com/example/
│   │   ├── config/         # 配置类
│   │   │   └── Knife4jConfig.java
│   │   ├── controller/     # 控制器
│   │   ├── service/        # 服务层
│   │   ├── mapper/         # 数据访问层
│   │   ├── entity/         # 实体类
│   │   ├── dto/            # 数据传输对象
│   │   ├── vo/             # 视图对象
│   │   └── Application.java
│   └── resources/
│       ├── mapper/         # MyBatis映射文件
│       └── application.yml
└── test/                   # 测试代码`,
    giteeUrl: "https://gitee.com/cheng-long-x/knife4j-spring-boot-tem",
    documentationUrl: "https://knife4j.xiaominfo.com/"
  },
  {
    id: "nest-admin",
    name: "NestJS Admin",
    description: "基于NestJS的企业级后端API框架",
    fullDescription: "使用NestJS构建的现代化企业级API开发模板。采用装饰器和依赖注入，集成了TypeORM、Redis、JWT等技术栈，提供完整的RBAC权限管理和API文档。",
    logo: "https://nestjs.com/img/logo-small.svg",
    author: "NestJS Community",
    version: "2.1.3",
    updateTime: "2025-03-16",
    downloads: 32400,
    stars: 1156,
    language: "Node.js",
    difficulty: 3,
    techStack: ["NestJS", "TypeScript", "TypeORM", "Redis", "JWT", "Swagger"],
    features: ["装饰器支持", "RBAC权限", "依赖注入", "API文档", "数据验证", "缓存支持", "单元测试"],
    apiExamples: [
      {
        title: "创建用户接口",
        code: `app.post('/api/users', async (req: Request, res: Response) => {
  const { error } = userSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details });
  
  const user = await User.create(req.body);
  res.status(201).json({ success: true, data: user });
});`
      },
      {
        title: "中间件示例",
        code: `const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  if (!token) return res.status(401).json({ error: 'Access denied' });
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(400).json({ error: 'Invalid token' });
  }
};`
      }
    ],
    projectStructure: `src/
├── controllers/        # 控制器
├── middleware/         # 中间件
├── models/            # 数据模型
├── routes/            # 路由定义
├── services/          # 业务逻辑
├── utils/             # 工具函数
├── types/             # TypeScript类型
├── config/            # 配置文件
└── app.ts             # 应用入口`,
    giteeUrl: "https://gitee.com/example/express-typescript-api",
    documentationUrl: "https://expressjs.com/"
  },
  {
    id: "fastapi-python",
    name: "FastAPI Python",
    description: "高性能异步Python API框架",
    fullDescription: "FastAPI是一个现代、快速的Python Web框架，用于构建API。具有自动API文档、数据验证、异步支持等特性，性能媲美NodeJS和Go。",
    logo: "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png",
    author: "FastAPI Team",
    version: "0.104.1",
    updateTime: "2025-03-10",
    downloads: 32400,
    stars: 967,
    language: "Python",
    difficulty: 2,
    techStack: ["FastAPI", "SQLAlchemy", "Pydantic", "Alembic", "PostgreSQL", "Redis"],
    features: ["自动API文档", "数据验证", "异步支持", "依赖注入", "安全认证", "ORM集成", "高性能"],
    apiExamples: [
      {
        title: "创建API端点",
        code: `@app.post("/users/", response_model=UserResponse)
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
    db_user = User(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user`
      },
      {
        title: "数据模型定义",
        code: `class UserCreate(BaseModel):
    username: str
    email: EmailStr
    password: str
    
    class Config:
        schema_extra = {
            "example": {
                "username": "johndoe",
                "email": "john@example.com",
                "password": "secret123"
            }
        }`
      }
    ],
    projectStructure: `app/
├── api/
│   ├── v1/            # API版本1
│   └── deps.py        # 依赖项
├── core/
│   ├── config.py      # 配置
│   └── security.py    # 安全相关
├── models/            # 数据模型
├── schemas/           # Pydantic模式
├── services/          # 业务逻辑
├── db/                # 数据库相关
└── main.py            # 应用入口`,
    giteeUrl: "https://gitee.com/example/fastapi-python",
    documentationUrl: "https://fastapi.tiangolo.com/"
  },
  {
    id: "gin-golang-api",
    name: "Gin Golang API",
    description: "高性能Go语言API开发框架",
    fullDescription: "基于Gin框架的高性能Go语言API开发模板。具有出色的性能表现，集成了GORM、Redis、JWT等常用组件，适合构建高并发的API服务。",
    logo: "https://gin-gonic.com/favicons/favicon-32x32.png",
    author: "Gin Team",
    version: "1.9.1",
    updateTime: "2025-03-08",
    downloads: 19800,
    stars: 743,
    language: "Go",
    difficulty: 3,
    techStack: ["Gin", "GORM", "Redis", "JWT", "Swagger", "Zap"],
    features: ["高性能", "中间件支持", "ORM集成", "日志管理", "API文档", "错误处理", "数据验证"],
    apiExamples: [
      {
        title: "路由定义",
        code: `func SetupRoutes(r *gin.Engine) {
    api := r.Group("/api/v1")
    {
        api.POST("/login", controllers.Login)
        api.GET("/users", middleware.AuthMiddleware(), controllers.GetUsers)
        api.POST("/users", middleware.AuthMiddleware(), controllers.CreateUser)
    }
}`
      },
      {
        title: "控制器示例",
        code: `func CreateUser(c *gin.Context) {
    var user models.User
    if err := c.ShouldBindJSON(&user); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    
    if err := services.CreateUser(&user); err != nil {
        c.JSON(500, gin.H{"error": "Failed to create user"})
        return
    }
    
    c.JSON(201, gin.H{"data": user})
}`
      }
    ],
    projectStructure: `project/
├── controllers/       # 控制器
├── middleware/        # 中间件
├── models/           # 数据模型
├── services/         # 业务逻辑
├── utils/            # 工具函数
├── config/           # 配置文件
├── docs/             # API文档
├── go.mod            # Go模块
└── main.go           # 程序入口`,
    giteeUrl: "https://gitee.com/example/gin-golang-api",
    documentationUrl: "https://gin-gonic.com/"
  },
  {
    id: "aspnet-core-api",
    name: "ASP.NET Core API",
    description: "微软官方.NET Core API开发框架",
    fullDescription: "基于ASP.NET Core的企业级API开发模板。提供完整的认证授权、数据访问、缓存、日志等功能，支持Docker部署和微服务架构。",
    logo: "https://dotnet.microsoft.com/static/images/redesign/downloads-dotnet-logo.svg",
    author: "Microsoft",
    version: "7.0.0",
    updateTime: "2025-03-05",
    downloads: 22100,
    stars: 623,
    language: "C#",
    difficulty: 4,
    techStack: ["ASP.NET Core", "Entity Framework", "AutoMapper", "FluentValidation", "Swagger", "Serilog"],
    features: ["依赖注入", "中间件管道", "ORM支持", "自动映射", "数据验证", "API文档", "结构化日志"],
    apiExamples: [
      {
        title: "控制器定义",
        code: `[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;

    [HttpPost]
    public async Task<ActionResult<UserDto>> CreateUser([FromBody] CreateUserDto dto)
    {
        var user = await _userService.CreateUserAsync(dto);
        return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
    }
}`
      },
      {
        title: "服务注册",
        code: `public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(connectionString));
    
    services.AddScoped<IUserService, UserService>();
    services.AddAutoMapper(typeof(MappingProfile));
    services.AddFluentValidationAutoValidation();
}`
      }
    ],
    projectStructure: `src/
├── Controllers/       # 控制器
├── Services/         # 服务层
├── Models/           # 数据模型
├── DTOs/             # 数据传输对象
├── Data/             # 数据访问
├── Mappings/         # 对象映射
├── Validators/       # 数据验证
├── Middleware/       # 中间件
└── Program.cs        # 程序入口`,
    giteeUrl: "https://gitee.com/example/aspnet-core-api",
    documentationUrl: "https://docs.microsoft.com/aspnet/core/"
  },
  {
    id: "django-rest-api",
    name: "Django REST API",
    description: "基于Django REST Framework的API开发框架",
    fullDescription: "Django REST Framework是一个强大灵活的工具包，用于构建Web API。提供序列化、认证、权限、分页等完整功能。",
    logo: "https://www.django-rest-framework.org/img/logo.png",
    author: "Django Team",
    version: "3.14.0",
    updateTime: "2025-03-02",
    downloads: 15600,
    stars: 567,
    language: "Python",
    difficulty: 3,
    techStack: ["Django", "Django REST Framework", "PostgreSQL", "Celery", "Redis", "JWT"],
    features: ["ORM支持", "序列化器", "视图集", "权限系统", "分页", "API浏览", "测试框架"],
    apiExamples: [
      {
        title: "视图集定义",
        code: `class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return User.objects.filter(is_active=True)`
      },
      {
        title: "序列化器",
        code: `class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password']
    
    def create(self, validated_data):
        password = validated_data.pop('password')
        user = User.objects.create_user(**validated_data)
        user.set_password(password)
        user.save()
        return user`
      }
    ],
    projectStructure: `project/
├── apps/
│   ├── users/        # 用户应用
│   ├── api/          # API应用
│   └── common/       # 通用模块
├── config/
│   ├── settings/     # 配置文件
│   └── urls.py       # URL配置
├── requirements/     # 依赖文件
└── manage.py         # Django管理脚本`,
    giteeUrl: "https://gitee.com/example/django-rest-api",
    documentationUrl: "https://www.django-rest-framework.org/"
  }
])

// 计算属性
const filteredTemplates = computed(() => {
  let filtered = templates.value

  // 按语言筛选
  if (activeLanguage.value !== "all") {
    filtered = filtered.filter(template =>
      template.language.toLowerCase().includes(activeLanguage.value.toLowerCase())
    )
  }

  // 按搜索文本筛选
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(searchLower)
      || template.description.toLowerCase().includes(searchLower)
      || template.techStack.some(tech => tech.toLowerCase().includes(searchLower))
    )
  }

  return filtered
})

const totalDownloads = computed(() => {
  return templates.value.reduce((total, template) => total + template.downloads, 0)
})

// 方法
function getLanguageTagType(language: string) {
  const typeMap: Record<string, string> = {
    "Java": "danger",
    "Node.js": "success",
    "Python": "warning",
    "Go": "primary",
    "C#": "info"
  }
  return typeMap[language] || ""
}

function getTechIcon(tech: string) {
  // 这里返回技术栈对应的图标URL
  const iconMap: Record<string, string> = {
    "Spring Boot": "https://spring.io/img/spring-2.svg",
    "Express.js": "https://expressjs.com/images/express-facebook-share.png",
    "FastAPI": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png",
    "Gin": "https://gin-gonic.com/favicons/favicon-32x32.png",
    "Django": "https://www.django-rest-framework.org/img/logo.png",
    "ASP.NET Core": "https://dotnet.microsoft.com/static/images/redesign/downloads-dotnet-logo.svg",
    "MySQL": "https://www.mysql.com/common/logos/logo-mysql-170x115.png",
    "PostgreSQL": "https://www.postgresql.org/media/img/about/press/elephant.png",
    "Redis": "https://redis.io/images/redis-white.png",
    "MongoDB": "https://www.mongodb.com/assets/images/global/favicon.ico"
  }
  return iconMap[tech] || `https://via.placeholder.com/32x32?text=${tech.charAt(0)}`
}

function formatNumber(num: number) {
  if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`
  }
  return num.toString()
}

function viewTemplate(template: ApiTemplate) {
  selectedTemplate.value = template
  detailDialogVisible.value = true
}

async function downloadTemplate(template: ApiTemplate) {
  try {
    ElMessage.success(`正在准备下载 ${template.name}...`)

    // 这里后期替换为真实的下载逻辑
    window.open(`${template.giteeUrl}/releases`, "_blank")

    // 更新下载次数
    template.downloads++
  } catch (error) {
    ElMessage.error("下载失败，请稍后重试")
    console.error("下载失败:", error)
  }
}

function viewDocumentation(template: ApiTemplate) {
  if (template.documentationUrl) {
    window.open(template.documentationUrl, "_blank")
  } else {
    ElMessage.info("该模板暂无文档链接")
  }
}

function openGiteeRepo(template: ApiTemplate) {
  window.open(template.giteeUrl, "_blank")
}

function loadMore() {
  loading.value = true
  // 模拟加载更多数据
  setTimeout(() => {
    loading.value = false
    hasMore.value = false
    ElMessage.info("已加载全部模板")
  }, 1000)
}

onMounted(() => {
  // 页面加载完成后的初始化操作
})
</script>

<style scoped lang="scss">
.api-templates-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 16px;

  // 确保容器能够完全包含内容
  display: flex;
  flex-direction: column;

  // 使用全屏宽度，不限制最大宽度
  width: 100%;
  box-sizing: border-box;

  .page-header {
    margin-bottom: 24px;
    background: white;
    border-radius: 12px;
    padding: 24px 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-text {
        h1 {
          font-size: 36px;
          font-weight: 700;
          color: #2c3e50;
          margin: 0 0 8px 0;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }

        p {
          font-size: 16px;
          color: #7f8c8d;
          margin: 0;
        }
      }

      .header-stats {
        display: flex;
        gap: 32px;

        .stat-item {
          text-align: center;

          .stat-number {
            display: block;
            font-size: 28px;
            font-weight: 700;
            color: #3b82f6;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: #95a5a6;
          }
        }
      }
    }
  }

  .filters-section {
    margin-bottom: 20px;
    display: flex;
    gap: 24px;
    align-items: center;
    justify-content: space-between;
    background: white;
    border-radius: 12px;
    padding: 16px 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    .search-box {
      flex: 1;
      max-width: 420px;

      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: 8px;
          border: 1px solid #e1e5e9;
          box-shadow: none;
          transition: all 0.2s ease;

          &:hover {
            border-color: #c0c4cc;
          }

          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }
      }
    }

    .filter-tabs {
      .el-radio-group {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 3px;
        border: 1px solid #e9ecef;

        .el-radio-button {
          .el-radio-button__inner {
            border: none;
            background: transparent;
            color: #6c757d;
            font-weight: 500;
            padding: 8px 16px;
            border-radius: 6px;
            transition: all 0.2s ease;

            &:hover {
              background: rgba(64, 158, 255, 0.08);
              color: #409eff;
            }
          }

          &.is-active .el-radio-button__inner {
            background: #409eff;
            color: white;
            box-shadow: 0 1px 3px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }
  }

  .templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    .template-card {
      background: white;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);

        .cover-overlay {
          opacity: 1;
        }
      }

      .template-cover {
        position: relative;
        height: 200px;
        background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
        display: flex;
        align-items: center;
        justify-content: center;

        .framework-logo {
          img {
            max-width: 120px;
            max-height: 80px;
            object-fit: contain;
            background: white;
            padding: 12px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }
        }

        .cover-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          .overlay-actions {
            display: flex;
            gap: 12px;
          }
        }

        .language-tag {
          position: absolute;
          top: 12px;
          left: 12px;
        }

        .difficulty-badge {
          position: absolute;
          top: 12px;
          right: 12px;
          background: rgba(255, 255, 255, 0.9);
          padding: 6px 12px;
          border-radius: 20px;
        }
      }

      .template-info {
        padding: 20px;

        .template-title {
          font-size: 20px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 8px 0;
        }

        .template-description {
          font-size: 14px;
          color: #7f8c8d;
          line-height: 1.5;
          margin: 0 0 16px 0;
        }

        .template-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          font-size: 12px;
          color: #95a5a6;

          .meta-left,
          .meta-right {
            display: flex;
            gap: 12px;
            align-items: center;
          }

          .author,
          .version,
          .downloads,
          .stars {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }

        .template-features {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          align-items: center;
          margin-bottom: 16px;

          .more-features {
            font-size: 12px;
            color: #95a5a6;
          }
        }

        .tech-icons {
          display: flex;
          align-items: center;
          gap: 8px;

          .tech-icon {
            width: 32px;
            height: 32px;
            border-radius: 6px;
            overflow: hidden;
            border: 1px solid #e9ecef;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .more-tech {
            font-size: 12px;
            color: #95a5a6;
            padding: 6px 8px;
            background: #f8f9fa;
            border-radius: 4px;
          }
        }
      }
    }
  }

  .load-more {
    text-align: center;
    margin-top: 32px;
  }
}

// 对话框样式
:deep(.template-detail-dialog) {
  .el-dialog__body {
    padding: 0;
  }

  .template-detail {
    .detail-header {
      display: flex;
      gap: 24px;
      padding: 24px;
      border-bottom: 1px solid #ebeef5;

      .detail-logo {
        img {
          width: 120px;
          height: 120px;
          object-fit: contain;
          background: #f8f9fa;
          padding: 16px;
          border-radius: 12px;
          border: 1px solid #e9ecef;
        }
      }

      .detail-info {
        flex: 1;

        h2 {
          margin: 0 0 12px 0;
          color: #2c3e50;
        }

        .detail-description {
          color: #7f8c8d;
          line-height: 1.6;
          margin-bottom: 20px;
        }

        .detail-meta {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
          margin-bottom: 24px;

          .meta-item {
            display: flex;
            align-items: center;
            font-size: 14px;
            gap: 8px;

            .label {
              color: #95a5a6;
              width: 80px;
              flex-shrink: 0;
            }

            .value {
              color: #2c3e50;
              font-weight: 500;
            }
          }
        }

        .detail-actions {
          display: flex;
          gap: 12px;
        }
      }
    }

    .detail-content {
      padding: 24px;

      .content-section {
        margin-bottom: 32px;

        h3 {
          margin: 0 0 16px 0;
          color: #2c3e50;
          font-size: 18px;
        }

        .tech-stack-detail {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;

          .tech-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;

            img {
              width: 20px;
              height: 20px;
              object-fit: contain;
            }
          }
        }

        .features-list {
          list-style: none;
          padding: 0;
          margin: 0;

          li {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 0;
            border-bottom: 1px solid #f5f5f5;

            .el-icon {
              color: #67c23a;
            }
          }
        }

        .api-examples {
          .api-example {
            margin-bottom: 24px;

            h4 {
              margin: 0 0 12px 0;
              color: #2c3e50;
              font-size: 16px;
            }

            pre {
              background: #f8f9fa;
              border: 1px solid #e9ecef;
              border-radius: 8px;
              padding: 16px;
              overflow-x: auto;
              font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
              font-size: 13px;
              line-height: 1.4;

              code {
                color: #2c3e50;
              }
            }
          }
        }

        .project-structure {
          pre {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 16px;
            overflow-x: auto;
            font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
            font-size: 13px;
            line-height: 1.4;
            color: #2c3e50;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .api-templates-page {
    padding: 16px;

    .page-header .header-content {
      flex-direction: column;
      text-align: center;
      gap: 20px;
    }

    .filters-section {
      flex-direction: column;
      align-items: stretch;

      .search-box {
        max-width: none;
      }
    }

    .templates-grid {
      grid-template-columns: 1fr;
    }

    .template-detail .detail-header {
      flex-direction: column;

      .detail-logo img {
        width: 100px;
        height: 100px;
      }
    }
  }
}
</style>
